//
//  NewFeatureController.swift
//  SinaWeibo
//
//  Created by 小果 on 16/2/10.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit

// 可重用的标识符
private let NewFeatureID = "featureCell"
// 新特性图片的数量
private let NewFeatureCount = 4
class NewFeatureController: UICollectionViewController {
    // 实现init()的构造函数，方便外部的代码调用，不需要另外在指定布局属性
    init (){
        // 调用父类的默认构造函数
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册可重用的cell
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: NewFeatureID)

        prepareLayout()
    }
    
    // 准备布局
    private func prepareLayout() {
        // 获得当前的布局属性
        let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置布局的其他属性
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
    }

    // MARK: - UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return NewFeatureCount
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NewFeatureID, forIndexPath: indexPath) as! NewFeatureCell
        cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.greenColor()
        
        cell.imageIndex = indexPath.item
        return cell
        
    }
    
    // MARK: - UICollectionViewDelegate
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 取出当前显示的cell的indexpath
        let path = collectionView.indexPathsForVisibleItems().last!
        // 判断是否是最后一个cell
        if path.item == NewFeatureCount - 1 {
            // 获取cell
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.didAppearStartBtn()
        }
    }
}

// 新特性cell，用private来修饰，可以保证这个cell只会被当前的控制器调用,在当前的文件中，所有的private都是无效的
private class NewFeatureCell : UICollectionViewCell {
    // 新特性界面的图像索引属性
    private var imageIndex: Int = 0 {
        didSet{
            imageView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startBtn.hidden = true
        }
    }
    
    // 点击开始按钮，如果类是private，即便没有对方法进行修饰，运行循环同样也无法调用监听方法
    @objc func clickStartBtn(){
     NSNotificationCenter.defaultCenter().postNotificationName(XGSwiftRootViewControllerNotification, object: nil)
    }
    
    // 动画显示开始体验按钮
    private func didAppearStartBtn() {
        startBtn.hidden = false
        
        startBtn.transform = CGAffineTransformMakeScale(0, 0)
        
        // Damping:弹性系数，0~1，系数越小弹性越大
        // Velocity:初始的速度
        UIView.animateWithDuration(2.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: [], animations: { () -> Void in
            
            self.startBtn.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

     required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
        setupUI()
     }
    
    // 设置新特性界面的内容
    private func setupUI(){
//        printLog(bounds)
        // 1、添加控件
        addSubview(imageView)
        addSubview(startBtn)
        
        // 2、指定布局
        imageView.frame = bounds
        
        // 自动布局的约束是添加在父视图上的
        startBtn.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: startBtn, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: startBtn, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: -160))
        
        
    }
    
    // MARK：- 懒加载属性
    // 图像视图
    private lazy var imageView = UIImageView()
    // 开始体验按钮
    private lazy var startBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        btn.addTarget(self, action: "clickStartBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
}



